package com.xiaoyu.lingdian.controller;

import java.io.BufferedOutputStream;
import java.io.StringReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.xml.sax.InputSource;

import com.xiaoyu.lingdian.controller.BaseController;
import com.xiaoyu.lingdian.entity.CoreAttachment;
import com.xiaoyu.lingdian.entity.CoreCartOrder;
import com.xiaoyu.lingdian.entity.CoreCartOrderDetail;
import com.xiaoyu.lingdian.entity.CoreIntegral;
import com.xiaoyu.lingdian.entity.CoreBookingRecord;
import com.xiaoyu.lingdian.entity.CorePointsOrder;
import com.xiaoyu.lingdian.entity.CorePointsProduct;
import com.xiaoyu.lingdian.entity.CoreRepairOrder;
import com.xiaoyu.lingdian.entity.CoreShoppingCart;
import com.xiaoyu.lingdian.entity.CoreUser;
import com.xiaoyu.lingdian.entity.weixin.Constant;
import com.xiaoyu.lingdian.entity.weixin.PayPackage;
import com.xiaoyu.lingdian.entity.weixin.TemplateData;
import com.xiaoyu.lingdian.entity.weixin.WxPayResult;
import com.xiaoyu.lingdian.entity.weixin.WxTemplate;
import com.xiaoyu.lingdian.service.CoreAttachmentService;
import com.xiaoyu.lingdian.service.CoreCartOrderDetailService;
import com.xiaoyu.lingdian.service.CoreCartOrderService;
import com.xiaoyu.lingdian.service.CoreIntegralService;
import com.xiaoyu.lingdian.service.CoreBookingRecordService;
import com.xiaoyu.lingdian.service.CorePointsOrderService;
import com.xiaoyu.lingdian.service.CorePointsProductService;
import com.xiaoyu.lingdian.service.CoreRepairOrderService;
import com.xiaoyu.lingdian.service.CoreShoppingCartService;
import com.xiaoyu.lingdian.service.CoreUserService;
import com.xiaoyu.lingdian.tool.RandomUtil;
import com.xiaoyu.lingdian.tool.SystemUtil;
import com.xiaoyu.lingdian.tool.encrypt.Sha1Util;
import com.xiaoyu.lingdian.tool.init.ConfigIni;
import com.xiaoyu.lingdian.tool.out.ResultMessageBuilder;
import com.xiaoyu.lingdian.tool.wx.GetExistAccessToken;
import com.xiaoyu.lingdian.tool.wx.GetWxOrderno;
import com.xiaoyu.lingdian.tool.wx.RequestHandler;
import com.xiaoyu.lingdian.tool.wx.TenpayUtil;
import com.xiaoyu.lingdian.tool.wx.WeixinUtil;

@Controller
@RequestMapping(value="/pay")
public class PayController extends BaseController {

	/**
	 * 用户表
	 */
	@Autowired
	private CoreUserService coreUserService;		
	
	/**
	 * 积分攻略表
	 */
	@Autowired
	private CoreIntegralService coreIntegralService;
	
	/**
	 * 预约记录表
	 */
	@Autowired
	private CoreBookingRecordService coreBookingRecordService;
	
	/**
	 * 商品表
	 */
	@Autowired
	private CorePointsProductService corePointsProductService;
	
	/**
	 * 商品订单表
	 */
	@Autowired
	private CorePointsOrderService corePointsOrderService;
	
	/**
	* CoreRepairOrder表
	*/
	@Autowired
	private CoreRepairOrderService coreRepairOrderService;
	
	/**
	 * 附件表
	 */
	@Autowired
	private CoreAttachmentService coreAttachmentService;
	
	/**
	 * 用户购物车订单
	 */
	@Autowired
	private CoreCartOrderService coreCartOrderService;
	
	/**
	 * 用户购物车订单详情
	 */
	@Autowired
	private CoreCartOrderDetailService coreCartOrderDetailService;
	
	/**
	 * 用户购物车
	 */
	@Autowired
	private CoreShoppingCartService coreShoppingCartService;	
	
	/**
	 * 预约支付获取请求预支付id报文
	 * 
	 * @param crkrdUuid 预约记录UUID
	 * @param zfFee 支付金额
	 * @param totalFee 原总金额
	 * @param syScore 所用积分
	 * @param dkFee 抵扣费用
	 * @param body 商品描述
	 * @param userUuid 用户UUID
	 * @param openId  微信用户公众号
	 * @param attach 附加数据 必传，暂无用，随便传一个字符
	 * @param response
	 */
	@RequestMapping(value = "/get/package/kuaidi", method = RequestMethod.POST)
	public void getPackageKuaidi(String crkrdUuid, Double zfFee, Double totalFee, Integer syScore, Double dkFee, String body, String userUuid, 
			String openId, String attach, HttpServletResponse response) {
		logger.info("[PayController.getPackageKuaidi]:end getPackageKuaidi.");
		if (StringUtils.isBlank(crkrdUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入预约记录UUID！"), response);
			return;
		}
		if(null == zfFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入支付价格！"), response);
			return;
		}
		if(null == totalFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入总价！"), response);
			return;
		}
		if(null == syScore) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入所用积分！"), response);
			return;
		}
		if(null == dkFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入抵扣费用！"), response);
			return;
		}
		if (StringUtils.isBlank(body)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入商品描述！"), response);
			return;
		}
		if (StringUtils.isBlank(userUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入用户UUID！"), response);
			return;
		}
		if (StringUtils.isBlank(openId)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入微信用户公众号！"), response);
			return;
		}
		if (StringUtils.isBlank(attach)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "附加数据必传！"), response);
			return;
		}
		
		//2）每消费1元可获得1积分，（用积分消费不产生积分）
		//3）每累计20积分可抵扣1元费用		
		double value = zfFee + dkFee;        
		//计算总价与抵扣价格是否相等
		if (totalFee != value) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "计算出的总价与支付价格和抵扣费用不等！"), response);
			return;
		}	
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(userUuid);
		coreUser = coreUserService.getCoreUser(coreUser);
		if (coreUser.getCrusrPoints() < syScore) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "积分不足，快去获得积分吧！"), response);
			return;
		}
		
		logger.info("[PayController.getPackageKuaidi]:end getPackageKuaidi.支付："+zfFee +"抵扣："+ dkFee +"总价："+totalFee );
		
		//更新订单为支付中
		CoreBookingRecord coreBookingRecord = new CoreBookingRecord();
		coreBookingRecord.setCrkrdUuid(crkrdUuid);
		coreBookingRecord.setCrkrdDkFee(dkFee.toString());
		coreBookingRecord.setCrkrdSjFee(zfFee.toString());
		coreBookingRecord.setCrkrdStatus(4); 						//支付中
		coreBookingRecord.setCrkrdTotal(totalFee.toString());		
		coreBookingRecord.setCrkrdUdate(new Date());
		coreBookingRecord.setCrkrdSyScore(syScore.toString());
		coreBookingRecordService.updateCoreBookingRecord(coreBookingRecord);		
		
		PayPackage finaPackage = getPackage(crkrdUuid, zfFee, body, openId, "预约费用");
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "获取package成功", finaPackage), response);
		logger.info("[PayController.getPackageKuaidi]:end getPackageKuaidi.");
	}
	
	/**
	 * 商品订单支付获取请求预支付id报文
	 * 
	 * @param crporGoodsUuid 商品UUID
	 * @param crporGoodsName
	 * @param crporName 收货人姓名
	 * @param crporTel 手机号码
	 * @param crporMail 邮政编码
	 * @param crporCity 所在省市
	 * @param crporAddress 详细地址
	 * @param crporNumber 数量
	 * @param crporPrice 单价
	 * @param crporRemarks 备注
	 * @param uuids
	 * @param zfFee 支付金额
	 * @param totalFee 原总金额
	 * @param syScore 所用积分
	 * @param dkFee 抵扣费用
	 * @param body 商品描述
	 * @param userUuid 用户UUID
	 * @param openId  微信用户公众号
	 * @param attach 附加数据 必传，暂无用，随便传一个字符
	 * @param response
	 */
	@RequestMapping(value = "/get/package/shangpin", method = RequestMethod.POST)
	public void getPackageShangpin(String crporGoodsUuid, String crporGoodsName, String crporName, String crporTel, String crporMail, 
			String crporCity, String crporAddress, Integer crporNumber, String crporPrice, String crporRemarks, String uuids,
			Double zfFee, Double totalFee, Integer syScore, Double dkFee, String body, String userUuid, 
			String openId, String attach, HttpServletResponse response) {
		logger.info("[PayController.getPackageShangpin]:end getPackageShangpin.");
		if (StringUtils.isBlank(crporGoodsUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入商品！"), response);
			return;
		}
		if (StringUtils.isBlank(crporGoodsName)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入商品名称！"), response);
			return;
		}
		if (StringUtils.isBlank(crporName)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入收货人！"), response);
			return;
		}
		if (StringUtils.isBlank(crporTel)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入收货人联系方式！"), response);
			return;
		}
		if (StringUtils.isBlank(crporCity)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入省市区！"), response);
			return;
		}
		if (StringUtils.isBlank(crporAddress)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入收货人详细地址！"), response);
			return;
		}
		if (null == crporNumber || 0 == crporNumber) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入购买数量！"), response);
			return;
		}
		if (StringUtils.isBlank(crporPrice)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入单价！"), response);
			return;
		}
		if(null == zfFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入支付价格！"), response);
			return;
		}
		if(null == totalFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入总价！"), response);
			return;
		}
		if(null == syScore) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入所用积分！"), response);
			return;
		}
		if(null == dkFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入抵扣费用！"), response);
			return;
		}
		if (StringUtils.isBlank(body)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入商品描述！"), response);
			return;
		}
		if (StringUtils.isBlank(userUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入用户UUID！"), response);
			return;
		}
		if (StringUtils.isBlank(openId)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入微信用户公众号！"), response);
			return;
		}
		if (StringUtils.isBlank(attach)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "附加数据必传！"), response);
			return;
		}
		
		double price = 0;
		double totalPrice = 0;
		try {
			price = Double.parseDouble(crporPrice);
			totalPrice = crporNumber * price;
		} catch (Exception e) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "单价格式不正确！"), response);
			return;
		}
		if (totalPrice != totalFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "计算出的总价与返回总价不相等！"), response);
			return;
		}
		double value = zfFee + dkFee;
		// 计算总价与抵扣价格是否相等
		if (totalFee != value) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "计算出的总价与支付价格和抵扣费用不等！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(userUuid);
		coreUser = coreUserService.getCoreUser(coreUser);
		if (coreUser.getCrusrPoints() < syScore) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "积分不足，快去获得积分吧！"), response);
			return;
		}
		
		//添加商品订单为支付中
		CorePointsOrder corePointsOrder = new CorePointsOrder();
		String uuid = "SP"+RandomUtil.generateString(14);
		corePointsOrder.setCrporUuid(uuid);
		corePointsOrder.setCrporCity(crporCity);
		corePointsOrder.setCrporAddress(crporAddress);
		corePointsOrder.setCrporCdate(new Date());
		corePointsOrder.setCrporGoodsName(crporGoodsName);
		corePointsOrder.setCrporGoodsUuid(crporGoodsUuid);
		corePointsOrder.setCrporMail(crporMail);
		corePointsOrder.setCrporName(crporName);
		corePointsOrder.setCrporNumber(crporNumber);
		corePointsOrder.setCrporPrice(crporPrice);
		corePointsOrder.setCrporRemarks(crporRemarks);
		corePointsOrder.setCrporStatus(1); //支付中
		corePointsOrder.setCrporTel(crporTel);
		corePointsOrder.setCrporTotal(totalFee.toString());
		corePointsOrder.setCrporUser(userUuid);
		corePointsOrder.setCrporSjFee(zfFee.toString());
		corePointsOrder.setCrporSyScore(syScore.toString());
		corePointsOrder.setCrporDkFee(dkFee.toString());
		corePointsOrderService.insertCorePointsOrder(corePointsOrder);
		// 添加商品封面
		if (!StringUtils.isBlank(uuids)) {
			CoreAttachment coreAttachment = new CoreAttachment();
			String[] uuidModel = uuids.split("\\|");
			for (int i = 0; i < uuidModel.length; i++) {
				coreAttachment = new CoreAttachment();
				coreAttachment.setCratmUuid(uuidModel[i]);
				coreAttachment = coreAttachmentService
						.getCoreAttachment(coreAttachment);
				if (coreAttachment != null) {
					CoreAttachment attachment = new CoreAttachment();
					attachment.setCratmCdate(new Date());
					attachment.setCratmDir(coreAttachment.getCratmDir());
					attachment.setCratmExtension(coreAttachment
							.getCratmExtension());
					attachment.setCratmBusUuid(uuid);
					attachment.setCratmFileName(coreAttachment
							.getCratmFileName());
					attachment.setCratmHeight(coreAttachment.getCratmHeight());
					attachment.setCratmStatus(coreAttachment.getCratmStatus());
					attachment.setCratmType(coreAttachment.getCratmType());
					attachment.setCratmWidth(coreAttachment.getCratmWidth());
					String uuid1 = RandomUtil.generateString(16);
					attachment.setCratmUuid(uuid1);
					coreAttachmentService.insertCoreAttachment(attachment);
				}
			}
		}
		PayPackage finaPackage = getPackage(uuid, totalFee, body, openId, crporGoodsName);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "获取package成功", finaPackage), response);
		logger.info("[PayController.getPackageShangpin]:end getPackageShangpin.");
	}
	
	/**
	 * 购物车订单支付
	 * @param crporName
	 * @param crporTel
	 * @param crporMail
	 * @param crporCity
	 * @param crporAddress
	 * @param crporNumber
	 * @param crporPrice
	 * @param crporRemarks
	 * @param uuids
	 * @param zfFee
	 * @param totalFee
	 * @param syScore
	 * @param dkFee
	 * @param body
	 * @param userUuid
	 * @param openId
	 * @param attach
	 * @param goodsInfo
	 * @param response
	 */
	@RequestMapping(value = "/get/package/storeCart", method = RequestMethod.POST)
	public void getPackageStoreCart(String crporName, String crporTel, String crporMail, 
			String crporCity, String crporAddress, Integer crporNumber, String crporPrice, String crporRemarks, String uuids,
			Double zfFee, Double totalFee, Integer syScore, Double dkFee, String body, String userUuid, 
			String openId, String attach,String goodsInfo, HttpServletResponse response) {
		logger.info("[PayController.getPackageStoreCart]:end getPackageStoreCart.");
				
		CoreCartOrder coreCartOrder = new CoreCartOrder();
		String uuid = "CART" + RandomUtil.generateString(12);
		coreCartOrder.setCrporUuid(uuid);
		coreCartOrder.setCrporUser(userUuid);
		coreCartOrder.setCrporCdate(new Date());
		coreCartOrder.setCrporAddress(crporAddress);
		coreCartOrder.setCrporCity(crporCity);
		coreCartOrder.setCrporTel(crporTel);
		coreCartOrder.setCrporMail(crporMail);
		coreCartOrder.setCrporName(crporName);			
		coreCartOrder.setCrporRemarks(crporRemarks);
		coreCartOrder.setCrporTotal(totalFee.toString());
		coreCartOrder.setCrporDkFee(dkFee.toString());
		coreCartOrder.setCrporSjFee(zfFee.toString());
		coreCartOrder.setCrporSyScore(syScore.toString());
		coreCartOrder.setCrporStatus(1);   //处理状态:1支付中2支付成功3支付失败4已发货5交易成功
		coreCartOrderService.insertCoreCartOrder(coreCartOrder);
		
		logger.info("[PayController.getPackageStoreCart].goodsInfo"+goodsInfo);
		
		String[] goods = goodsInfo.split("#");
		for(int i =0;i<goods.length;i++){
			String[] good = goods[i].split("~");
			CoreCartOrderDetail coreCartOrderDetail = new CoreCartOrderDetail();
			coreCartOrderDetail.setCriglGoodsName(good[0]);
			coreCartOrderDetail.setCriglGoodsPrice(good[1].trim().substring(1));
			coreCartOrderDetail.setCriglGoodsAmount(Integer.valueOf(good[2]));			
			coreCartOrderDetail.setCriglGoodsScore(Integer.valueOf(good[3]));
			coreCartOrderDetail.setCrporCdate(new Date());
			coreCartOrderDetail.setCrporOrderUuid(uuid);		
			coreCartOrderDetail.setCrporUuid(RandomUtil.generateString(16));
			coreCartOrderDetailService.insertCoreCartOrderDetail(coreCartOrderDetail);
		}
		
		//清空用户购物车
		CoreShoppingCart coreShoppingCart = new CoreShoppingCart();
		coreShoppingCart.setCriglUser(userUuid);
		coreShoppingCartService.deleteCoreShoppingCartByUser(coreShoppingCart);
		
		PayPackage finaPackage = getPackage(uuid, totalFee, body, openId, uuid);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "获取package成功", finaPackage), response);
		logger.info("[PayController.getPackageStoreCart]:end getPackageStoreCart.");
	}
	
	/**
	 * 维修订单支付获取请求预支付id报文
	 * 
	 * @param crrorTel 下单用户手机号
	 * @param crrorGoods 下单详情
	 * @param crrorRemarks 备注
	 * @param uuids
	 * @param zfFee 支付金额
	 * @param totalFee 原总金额
	 * @param syScore 所用积分
	 * @param dkFee 抵扣费用
	 * @param body 商品描述
	 * @param userUuid 用户UUID
	 * @param openId  微信用户公众号
	 * @param attach 附加数据 必传，暂无用，随便传一个字符
	 * @param response
	 */
	@RequestMapping(value = "/get/package/weixiu", method = RequestMethod.POST)
	public void getPackageWeixiu(String crrorTel, String crrorGoods, String crrorRemarks, String uuids,
			Double zfFee, Double totalFee, Integer syScore, Double dkFee, String body, String userUuid, 
			String openId, String attach, HttpServletResponse response) {
		logger.info("[PayController.getPackageWeixiu]:end getPackageWeixiu.");
		if (StringUtils.isBlank(crrorTel)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入下单用户手机号！"), response);
			return;
		}
		if (StringUtils.isBlank(crrorGoods)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入下单详情！"), response);
			return;
		}
		if(null == zfFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入支付价格！"), response);
			return;
		}
		if(null == totalFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入总价！"), response);
			return;
		}
		if(null == syScore) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入所用积分！"), response);
			return;
		}
		if(null == dkFee) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入抵扣费用！"), response);
			return;
		}
		if (StringUtils.isBlank(body)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入商品描述！"), response);
			return;
		}
		if (StringUtils.isBlank(userUuid)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入用户UUID！"), response);
			return;
		}
		if (StringUtils.isBlank(openId)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "请输入微信用户公众号！"), response);
			return;
		}
		if (StringUtils.isBlank(attach)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "附加数据必传！"), response);
			return;
		}
		double value = zfFee + dkFee;
		//计算总价与抵扣价格是否相等
		if (totalFee != value) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "计算出的总价与支付价格和抵扣费用不等！"), response);
			return;
		}
		CoreUser coreUser = new CoreUser();
		coreUser.setCrusrUuid(userUuid);
		coreUser = coreUserService.getCoreUser(coreUser);
		if (coreUser.getCrusrPoints() < syScore) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "积分不足，快去获得积分吧！"), response);
			return;
		}
		//添加维修订单为支付中
		CoreRepairOrder coreRepairOrder = new CoreRepairOrder();
		String uuid = "WX"+RandomUtil.generateString(14);
		coreRepairOrder.setCrrorUuid(uuid);
		coreRepairOrder.setCrrorGoods(crrorGoods);		
		coreRepairOrder.setCrrorRemarks(crrorRemarks);
		coreRepairOrder.setCrrorTel(crrorTel);
		coreRepairOrder.setCrrorCdate(new Date());
		coreRepairOrder.setCrrorStatus(1); //支付中
		coreRepairOrder.setCrrorTotal(totalFee.toString());
		coreRepairOrder.setCrrorUser(userUuid);
		coreRepairOrder.setCrrorSjFee(zfFee.toString());
		coreRepairOrder.setCrrorSyScore(syScore.toString());
		coreRepairOrder.setCrrorDkFee(dkFee.toString());
		coreRepairOrderService.insertCoreRepairOrder(coreRepairOrder);
		PayPackage finaPackage = getPackage(uuid, totalFee, body, openId, "维修订单");
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "获取package成功", finaPackage), response);
		logger.info("[PayController.getPackageWeixiu]:end getPackageWeixiu.");
	}
	
	/**
	 * 获取请求预支付id报文
	 * 
	 * @param orderId
	 * @param fee
	 * @param body
	 * @param openId
	 * @param attach
	 */
	public PayPackage getPackage(String orderId, Double fee, String body, String openId, String attach) {
		String spbill_create_ip = SystemUtil.getIPInfo(); //订单生成的机器 IP
		// 总金额以分为单位，不带小数点
		String totalFee = getMoney(fee.toString());
		String trade_type = "JSAPI";
		// 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
		String notify_url = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "notifyurl", Constant.NOTIFY_URL);		
		// 商户号
		String mch_id = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "partner", Constant.PARTNER);
		String appid = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appid", Constant.APP_ID);
		String appsecret = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appsecret", Constant.APP_SECRET);
		String partnerkey = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "partnerkey", Constant.PARTNERKEY);
		// 随机字符串
		String nonce_str = getNonceStr();
		// 商户订单号
		String out_trade_no = orderId;
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);
		packageParams.put("attach", attach);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("total_fee", totalFee);
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", notify_url);
		packageParams.put("trade_type", trade_type);
		packageParams.put("openid", openId);
		RequestHandler reqHandler = new RequestHandler(null, null);
		reqHandler.init(appid, appsecret, partnerkey);
		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" 
				+ "<appid>" + appid + "</appid>" 
				+ "<mch_id>" + mch_id + "</mch_id>"
				+ "<nonce_str>" + nonce_str + "</nonce_str>" 
				+ "<sign>" + sign + "</sign>"
				+ "<body><![CDATA[" + body + "]]></body>" 
				+ "<out_trade_no>" + out_trade_no + "</out_trade_no>" 
				+ "<attach>" + attach + "</attach>" 
				+ "<total_fee>" + totalFee + "</total_fee>"
				+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" 
				+ "<notify_url>" + notify_url + "</notify_url>" 
				+ "<trade_type>" + trade_type + "</trade_type>" 
				+ "<openid>" + openId + "</openid>" 
				+ "</xml>";
		String prepay_id = "";
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		prepay_id = GetWxOrderno.getPayNo(createOrderURL, xml);
		logger.info("获取到的预支付ID：" + prepay_id);
		// 获取prepay_id后，拼接最后请求支付所需要的package
		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String timestamp = Sha1Util.getTimeStamp();
		String packages = "prepay_id=" + prepay_id;
		finalpackage.put("appId", appid);
		finalpackage.put("timeStamp", timestamp);
		finalpackage.put("nonceStr", nonce_str);
		finalpackage.put("package", packages);
		finalpackage.put("signType", "MD5");
		// 要签名
		String finalsign = reqHandler.createSign(finalpackage);
		String finaPackage = "\"appId\":\"" + appid + "\",\"timeStamp\":\""
				+ timestamp + "\",\"nonceStr\":\"" + nonce_str
				+ "\",\"package\":\"" + packages + "\",\"signType\" : \"MD5"
				+ "\",\"paySign\":\"" + finalsign + "\"";
		PayPackage payPackage = new PayPackage();
		payPackage.setAppId(appid);
		payPackage.setNonceStr(nonce_str);
		payPackage.setPackages(packages);
		payPackage.setPaySign(finalsign);
		payPackage.setSignType("MD5");
		payPackage.setTimeStamp(timestamp);
		logger.info("V3 jsApi package:" + finaPackage);
		return payPackage;
	}
	
	/**
	 * 获取随机字符串
	 * 
	 * @return
	 */
	public static String getNonceStr() {
		// 随机数
		String currTime = TenpayUtil.getCurrTime();
		// 8位日期
		String strTime = currTime.substring(8, currTime.length());
		// 四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		return strTime + strRandom;
	}
	
	/**
	 * 元转换成分
	 * 
	 * @param money
	 * @return
	 */
	public static String getMoney(String amount) {
		if (amount == null) {
			return "";
		}
		// 金额转化为分为单位
		String currency = amount.replaceAll("\\$|\\￥|\\,", ""); // 处理包含 ￥  或者$的金额
		int index = currency.indexOf(".");
		int length = currency.length();
		Long amLong = 0l;
		if (index == -1) {
			amLong = Long.valueOf(currency + "00");
		} else if (length - index >= 3) {
			amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
		} else if (length - index == 2) {
			amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
		} else {
			amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
		}
		return amLong.toString();
	}

	/**
	 * 回调函数
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/notify", method = RequestMethod.POST)	
	public String notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("微信支付回调数据开始");
		String inputLine;
		String notityXml = "";
		String resXml = "";
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("接收到的报文：" + notityXml);
		Map m = parseXmlToList(notityXml);
		WxPayResult wpr = new WxPayResult();
		wpr.setAppid(m.get("appid").toString());
		String attach = m.get("attach")==null?"":m.get("attach").toString();
		wpr.setAttach(attach);
		wpr.setBankType(m.get("bank_type").toString());
		wpr.setCashFee(m.get("cash_fee").toString());
		wpr.setFeeType(m.get("fee_type").toString());
		wpr.setIsSubscribe(m.get("is_subscribe").toString());
		wpr.setMchId(m.get("mch_id").toString());
		wpr.setNonceStr(m.get("nonce_str").toString());
		wpr.setOpenid(m.get("openid").toString());
		wpr.setOutTradeNo(m.get("out_trade_no").toString());
		wpr.setResultCode(m.get("result_code").toString());
		wpr.setSign(m.get("sign").toString());
		wpr.setTimeEnd(m.get("time_end").toString());
		wpr.setTotalFee(m.get("total_fee").toString());
		wpr.setTradeType(m.get("trade_type").toString());
		wpr.setTransactionId(m.get("transaction_id").toString());
		if ("SUCCESS".equals(wpr.getResultCode())) { // 支付成功
			GetExistAccessToken getExistAccessToken = GetExistAccessToken.getInstance();
			WxTemplate t = new WxTemplate();
			t.setUrl("");
			t.setTouser(wpr.getOpenid());
			t.setTopcolor("#000000");
			t.setTemplate_id(ConfigIni.getIniStrValue("WEIXIN_CONFIG", "modelId", ""));
			Map<String, TemplateData> map = new HashMap<String, TemplateData>();
			
			if (wpr.getOutTradeNo().startsWith("KD")) { //预约记录
				//更新订单为支付成功
				CoreBookingRecord coreBookingRecord = new CoreBookingRecord();
				coreBookingRecord.setCrkrdUuid(wpr.getOutTradeNo());
				coreBookingRecord.setCrkrdStatus(5); //支付成功		
				coreBookingRecord.setCrkrdUdate(new Date());
				coreBookingRecordService.updateCoreBookingRecord(coreBookingRecord);
				coreBookingRecord = coreBookingRecordService.getCoreBookingRecord(coreBookingRecord);
				if (coreBookingRecord != null) {
					CoreUser coreUser = new CoreUser();
					coreUser.setCrusrUuid(coreBookingRecord.getCrkrdUser());
					Integer crporSyScore = 0;
					try {
						crporSyScore = Integer.parseInt(coreBookingRecord.getCrkrdSyScore());
					} catch (Exception e) {
						logger.info("解析所用积分错误:" + coreBookingRecord.getCrkrdSyScore());
					}
					int points = 0;
					CoreIntegral coreIntegral = new CoreIntegral();
					coreIntegral.setCriglUuid("BBBBB");
					coreIntegral = coreIntegralService.getCoreIntegral(coreIntegral);
					if (coreIntegral != null) {
						String criglScore = coreIntegral.getCriglScore();
						points = Integer.valueOf(criglScore.substring(0, criglScore.length()-1));    //每消费1元可获得1积分
					}
					double fee = 0.0;
					try {
						fee = Double.parseDouble(coreBookingRecord.getCrkrdTotal());
					} catch (Exception e) {
						
					}
					int a = (int)Math.round((points * fee) / 10.0);
					
					//扣除用户积分
					coreUser.setCrusrPoints(crporSyScore);
					coreUserService.updateCoreUserPointsDesc(coreUser);
					
					//用户获得积分
					coreUser = new CoreUser();
					coreUser.setCrusrUuid(coreBookingRecord.getCrkrdUser());
					coreUser.setCrusrPoints(a);
					coreUserService.updateCoreUserPointsAdd(coreUser);
				}
				TemplateData firstData = new TemplateData();
				firstData.setColor("#000000");
				firstData.setValue("我们已收到您的预约费用，谢谢: )");
				map.put("first", firstData);
			}
			if (wpr.getOutTradeNo().startsWith("SP")) { //商品订单记录
				//更新订单为支付成功
				CorePointsOrder corePointsOrder = new CorePointsOrder();
				corePointsOrder.setCrporUuid(wpr.getOutTradeNo());
				corePointsOrder.setCrporStatus(2); //支付成功		
				corePointsOrder.setCrporUdate(new Date());
				corePointsOrderService.updateCorePointsOrder(corePointsOrder);
				corePointsOrder = corePointsOrderService.getCorePointsOrder(corePointsOrder);
				if (corePointsOrder != null) {
					CoreUser coreUser = new CoreUser();
					coreUser.setCrusrUuid(corePointsOrder.getCrporUser());
					Integer crporSyScore = 0;
					try {
						crporSyScore = Integer.parseInt(corePointsOrder.getCrporSyScore());
					} catch (Exception e) {
						logger.info("解析所用积分错误:" + corePointsOrder.getCrporSyScore());
					}
					int points = 0;
					CoreIntegral coreIntegral = new CoreIntegral();
					coreIntegral.setCriglUuid("BBBBB");
					coreIntegral = coreIntegralService.getCoreIntegral(coreIntegral);
					if (coreIntegral != null) {
						String criglScore = coreIntegral.getCriglScore();
						points = Integer.valueOf(criglScore.substring(0, criglScore.length()-1));    //每消费1元可获得1积分
					}
					double fee = 0.0;
					try {
						fee = Double.parseDouble(corePointsOrder.getCrporTotal());
					} catch (Exception e) {
					}
					int a = (int)Math.round((points * fee) / 10.0);
					//扣除用户积分
					coreUser.setCrusrPoints(crporSyScore);
					coreUserService.updateCoreUserPointsDesc(coreUser);
					//用户获得积分
					coreUser = new CoreUser();
					coreUser.setCrusrUuid(corePointsOrder.getCrporUser());
					coreUser.setCrusrPoints(a);
					coreUserService.updateCoreUserPointsAdd(coreUser);
					// 减去库存
					CorePointsProduct corePointsProduct = new CorePointsProduct();
					corePointsProduct.setCrpopUuid(corePointsOrder.getCrporGoodsUuid());
					corePointsProduct.setCrpopStock(corePointsOrder.getCrporNumber());
					corePointsProductService.updateCorePointsProductDesc(corePointsProduct);
				}
				TemplateData firstData = new TemplateData();
				firstData.setColor("#000000");
				firstData.setValue("我们已收到您的货款，开始为您打包商品，请耐心等待: )");
				map.put("first", firstData);
			}
			if (wpr.getOutTradeNo().startsWith("CART")) { //商品购物车订单记录
				//更新购物车订单为支付成功
				CoreCartOrder coreCartOrder = new CoreCartOrder();
				coreCartOrder.setCrporUuid(wpr.getOutTradeNo());
				coreCartOrder.setCrporStatus(2); //支付成功		
				coreCartOrder.setCrporUdate(new Date());
				coreCartOrderService.updateCoreCartOrder(coreCartOrder);
				coreCartOrder = coreCartOrderService.getCoreCartOrder(coreCartOrder);
				if (coreCartOrder != null) {
					CoreUser coreUser = new CoreUser();
					coreUser.setCrusrUuid(coreCartOrder.getCrporUser());
					Integer crporSyScore = 0;
					try {
						crporSyScore = Integer.parseInt(coreCartOrder.getCrporSyScore());
					} catch (Exception e) {
						logger.info("解析所用积分错误:" + coreCartOrder.getCrporSyScore());
					}
					int points = 0;
					CoreIntegral coreIntegral = new CoreIntegral();
					coreIntegral.setCriglUuid("BBBBB");
					coreIntegral = coreIntegralService.getCoreIntegral(coreIntegral);
					if (coreIntegral != null) {
						String criglScore = coreIntegral.getCriglScore();
						points = Integer.valueOf(criglScore.substring(0, criglScore.length()-1));    //每消费1元可获得1积分
					}
					double fee = 0.0;
					try {
						fee = Double.parseDouble(coreCartOrder.getCrporTotal());
					} catch (Exception e) {
					}
					int a = (int)Math.round((points * fee) / 10.0);
					//扣除用户积分
					coreUser.setCrusrPoints(crporSyScore);
					coreUserService.updateCoreUserPointsDesc(coreUser);
					//用户获得积分
					coreUser = new CoreUser();
					coreUser.setCrusrUuid(coreCartOrder.getCrporUser());
					coreUser.setCrusrPoints(a);
					coreUserService.updateCoreUserPointsAdd(coreUser);
				}
				TemplateData firstData = new TemplateData();
				firstData.setColor("#000000");
				firstData.setValue("我们已收到您的货款，开始为您打包商品，请耐心等待: )");
				map.put("first", firstData);
			}
			if (wpr.getOutTradeNo().startsWith("WX")) { //维修记录
				//更新订单为支付成功
				CoreRepairOrder coreRepairOrder = new CoreRepairOrder();
				coreRepairOrder.setCrrorUuid(wpr.getOutTradeNo());
				coreRepairOrder.setCrrorStatus(2); //支付成功		
				coreRepairOrder.setCrrorUdate(new Date());
				coreRepairOrderService.updateCoreRepairOrder(coreRepairOrder);
				coreRepairOrder = coreRepairOrderService.getCoreRepairOrder(coreRepairOrder);
				if (coreRepairOrder != null) {
					CoreUser coreUser = new CoreUser();
					coreUser.setCrusrUuid(coreRepairOrder.getCrrorUser());
					Integer crporSyScore = 0;
					try {
						crporSyScore = Integer.parseInt(coreRepairOrder.getCrrorSyScore());
					} catch (Exception e) {
						logger.info("解析所用积分错误:" + coreRepairOrder.getCrrorSyScore());
					}
					int points = 0;
					CoreIntegral coreIntegral = new CoreIntegral();
					coreIntegral.setCriglUuid("BBBBB");
					coreIntegral = coreIntegralService.getCoreIntegral(coreIntegral);
					if (coreIntegral != null) {
						String criglScore = coreIntegral.getCriglScore();
						points = Integer.valueOf(criglScore.substring(0, criglScore.length()-1));    //每消费1元可获得1积分
					}
					double fee = 0.0;
					try {
						fee = Double.parseDouble(coreRepairOrder.getCrrorTotal());
					} catch (Exception e) {
					}
					int a = (int)Math.round((points * fee) / 10.0);
					//扣除用户积分
					coreUser.setCrusrPoints(crporSyScore);
					coreUserService.updateCoreUserPointsDesc(coreUser);
					//用户获得积分
					coreUser = new CoreUser();
					coreUser.setCrusrUuid(coreRepairOrder.getCrrorUser());
					coreUser.setCrusrPoints(a);
					coreUserService.updateCoreUserPointsAdd(coreUser);
				}
				TemplateData firstData = new TemplateData();
				firstData.setColor("#000000");
				firstData.setValue("我们已收到您的维修订单费用，我们将尽快联系您: )");
				map.put("first", firstData);
			}
			
			TemplateData orderMoneySum = new TemplateData();
			orderMoneySum.setColor("#000000");
			double fee = 0.0;
			try {
				fee = Double.parseDouble(wpr.getTotalFee())/100;
			} catch (Exception e) {
				logger.info("解析返回金额错误:" + wpr.getTotalFee());
			}
			orderMoneySum.setValue(fee+"");
			map.put("orderMoneySum", orderMoneySum);

			TemplateData orderProductName = new TemplateData();
			orderProductName.setColor("#000000");
			orderProductName.setValue(wpr.getAttach());
			map.put("orderProductName", orderProductName);

			TemplateData remarkData = new TemplateData();
			remarkData.setColor("#000000");
			remarkData.setValue("如有问题请直接在微信留言，我们将第一时间为您服务！");
			map.put("Remark", remarkData);

			t.setData(map);
			String jsonStr = JSONObject.fromObject(t).toString(); // 此处你应该代入自己的template
			String appid = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appid", Constant.APP_ID);
			String appsecret = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appsecret", Constant.APP_SECRET);
			String accessToken = getExistAccessToken.getExistAccessToken(appid, appsecret, "accessToken");
			WeixinUtil.sendTemplateMsg(jsonStr, accessToken);
			resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";
		} else {
			if (wpr.getOutTradeNo().startsWith("KD")) { //预约记录
				//更新订单为支付失败
				CoreBookingRecord coreBookingRecord = new CoreBookingRecord();
				coreBookingRecord.setCrkrdUuid(wpr.getOutTradeNo());
				coreBookingRecord.setCrkrdStatus(6); //支付失败		
				coreBookingRecord.setCrkrdUdate(new Date());
				coreBookingRecordService.updateCoreBookingRecord(coreBookingRecord);
			}
			if (wpr.getOutTradeNo().startsWith("SP")) { //商品订单记录
				//商品订单记录为支付失败
				CorePointsOrder corePointsOrder = new CorePointsOrder();
				corePointsOrder.setCrporUuid(wpr.getOutTradeNo());
				corePointsOrder.setCrporStatus(3); //支付失败		
				corePointsOrder.setCrporUdate(new Date());
				corePointsOrderService.updateCorePointsOrder(corePointsOrder);
			}
			if (wpr.getOutTradeNo().startsWith("CART")) { //购物车订单记录
				//更新购物车订单为支付失败
				CoreCartOrder coreCartOrder = new CoreCartOrder();
				coreCartOrder.setCrporUuid(wpr.getOutTradeNo());
				coreCartOrder.setCrporStatus(3); //支付失败		
				coreCartOrder.setCrporUdate(new Date());
				coreCartOrderService.updateCoreCartOrder(coreCartOrder);
			}
			if (wpr.getOutTradeNo().startsWith("WX")) { //维修记录
				//更新订单为支付失败
				CoreRepairOrder coreRepairOrder = new CoreRepairOrder();
				coreRepairOrder.setCrrorUuid(wpr.getOutTradeNo());
				coreRepairOrder.setCrrorStatus(3); //支付失败		
				coreRepairOrder.setCrrorUdate(new Date());
				coreRepairOrderService.updateCoreRepairOrder(coreRepairOrder);
			}
			resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
		}
		logger.info("微信支付回调数据结束");
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(resXml.getBytes());
		out.flush();
		out.close();
		return "paylogin";
	}

	/**
	 * 解析微信通知xml
	 * 
	 * @param xml
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static Map parseXmlToList(String xml) {
		Map retMap = new HashMap();
		try {
			StringReader read = new StringReader(xml);
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML
			InputSource source = new InputSource(read);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			// 通过输入源构造一个Document
			Document doc = (Document) sb.build(source);
			Element root = doc.getRootElement();// 指向根节点
			List<Element> es = root.getChildren();
			if (es != null && es.size() != 0) {
				for (Element element : es) {
					retMap.put(element.getName(), element.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}
	
	public static void main(String[] args) {
			String spbill_create_ip = SystemUtil.getIPInfo(); //订单生成的机器 IP
			// 总金额以分为单位，不带小数点
			String totalFee = getMoney("1");
			String trade_type = "JSAPI";
			// 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
			String notify_url = "http://jgj.hzlingdian.com/jgj/pay/notify";		
			// 商户号
			String mch_id = "1298298001";
			String appid = "wxd728dc50b5aa8ee9";
			String appsecret = "5dd5487549ca976997c0503a6b1bbee4";
			String partnerkey = "lingdianwulingdianwulingdianwuli";
			// 随机字符串
			String nonce_str = getNonceStr();
			// 商户订单号
			String out_trade_no = "111111111";
			SortedMap<String, String> packageParams = new TreeMap<String, String>();
			packageParams.put("appid", appid);
			packageParams.put("mch_id", mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", "购买商品");
			packageParams.put("attach", "1");
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", totalFee);
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", trade_type);
			packageParams.put("openid", "ozfbQv1Gd_y8FMgemUyvrKH4RMHU");
			RequestHandler reqHandler = new RequestHandler(null, null);
			reqHandler.init(appid, appsecret, partnerkey);
			String sign = reqHandler.createSign(packageParams);
			String xml = "<xml>" 
					+ "<appid>" + appid + "</appid>" 
					+ "<mch_id>" + mch_id + "</mch_id>"
					+ "<nonce_str>" + nonce_str + "</nonce_str>" 
					+ "<sign>" + sign + "</sign>"
					+ "<body><![CDATA[" + "购买商品" + "]]></body>" 
					+ "<out_trade_no>" + out_trade_no + "</out_trade_no>" 
					+ "<attach>1</attach>" 
					+ "<total_fee>" + totalFee + "</total_fee>"
					+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" 
					+ "<notify_url>" + notify_url + "</notify_url>" 
					+ "<trade_type>" + trade_type + "</trade_type>" 
					+ "<openid>" + "ozfbQv1Gd_y8FMgemUyvrKH4RMHU" + "</openid>" 
					+ "</xml>";
			String prepay_id = "";
			String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
			prepay_id = GetWxOrderno.getPayNo(createOrderURL, xml);
			System.out.println("获取到的预支付ID：" + prepay_id);
			// 获取prepay_id后，拼接最后请求支付所需要的package
			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			String timestamp = Sha1Util.getTimeStamp();
			String packages = "prepay_id=" + prepay_id;
			finalpackage.put("appId", appid);
			finalpackage.put("timeStamp", timestamp);
			finalpackage.put("nonceStr", nonce_str);
			finalpackage.put("package", packages);
			finalpackage.put("signType", "MD5");
			// 要签名
			String finalsign = reqHandler.createSign(finalpackage);
			String finaPackage = "\"appId\":\"" + appid + "\",\"timeStamp\":\""
					+ timestamp + "\",\"nonceStr\":\"" + nonce_str
					+ "\",\"package\":\"" + packages + "\",\"signType\" : \"MD5"
					+ "\",\"paySign\":\"" + finalsign + "\"";
			PayPackage payPackage = new PayPackage();
			payPackage.setAppId(appid);
			payPackage.setNonceStr(nonce_str);
			payPackage.setPackages(packages);
			payPackage.setPaySign(finalsign);
			payPackage.setSignType("MD5");
			payPackage.setTimeStamp(timestamp);
			System.out.println("V3 jsApi package:" + finaPackage);

	}
}